<template>
  <div>
    <!-- 添加界面 -->
    <el-button
      type="primary"
      @click="this.dialogFormToAdd = true"
      color="#FFB805"
      :disabled="!this.hasAuth('sys:project:add')"
      >添加</el-button
    >
    <el-dialog
      v-model="dialogFormToAdd"
      title="新增项目"
      top="2vh"
      @close="resetForm('InfoForm')"
    >
      <el-scrollbar height="700px" width="20%">
        <el-form
          ref="InfoForm"
          :model="InfoForm"
          label-width="100px"
          class="demo-ruleForm"
          enctype="multipart/form-data"
          :rules="rules"
          label-position="left"
        >
          <el-form-item label="项目编号" prop="projectNum">
            <el-input v-model="InfoForm.projectNum" type="text"></el-input>
          </el-form-item>
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="InfoForm.projectName" type="text"></el-input>
          </el-form-item>
          <el-form-item label="主持人" prop="hostname">
            <el-input v-model="InfoForm.hostname" type="text"></el-input>
          </el-form-item>
          <el-form-item label="团队成员" prop="member">
            <el-input v-model="InfoForm.member" type="text"></el-input>
          </el-form-item>
          <el-form-item label="本人排名" prop="ranking">
            <el-input v-model.number="InfoForm.ranking" type="text"></el-input>
          </el-form-item>
          <el-form-item label="主持单位" prop="hostUnit">
            <el-autocomplete
              v-model="InfoForm.hostUnit"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入主持单位"
              style="width: 100%"
              @select="handleSelectHostUnit"
              value-key="companyName"
              :trigger-on-focus="false"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="起始时间" prop="beginDate">
            <el-date-picker
              style="width: 100%"
              v-model="InfoForm.beginDate"
              type="date"
              placeholder="请选择起始时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结项时间" prop="endDate">
            <el-date-picker
              style="width: 100%"
              v-model="InfoForm.endDate"
              type="date"
              placeholder="请选择发表时间"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="项目总金额" prop="totalPrice">
            <el-input
              v-model.number="InfoForm.totalPrice"
              type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="项目类型" prop="projectType">
            <el-select
              v-model="InfoForm.projectType"
              placeholder="请选择项目类型"
              style="width: 100%"
              @change="typeChange"
            >
              <el-option
                v-for="item in projectType"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="合作单位"
            prop="cooperationUnit"
            v-show="useable"
          >
            <el-autocomplete
              v-model="InfoForm.cooperationUnit"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入合作单位"
              @select="handleSelectCooperation"
              value-key="companyName"
              :trigger-on-focus="false"
              style="width: 100%"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="项目级别" prop="level" v-show="useable">
            <el-select
              v-model="InfoForm.level"
              placeholder="请选择项目级别"
              style="width: 100%"
            >
              <el-option
                v-for="item in level"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目类别" prop="classification" v-show="useable">
            <el-select
              v-model="InfoForm.classification"
              placeholder="请选择项目类别"
              style="width: 100%"
            >
              <el-option
                v-for="item in classic"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="财政支持金额"
            prop="financePrice"
            v-show="useable"
          >
            <el-input
              v-model.number="InfoForm.financePrice"
              type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="自筹金额" prop="selfPrice" v-show="useable">
            <el-input
              v-model.number="InfoForm.selfPrice"
              type="text"
            ></el-input>
          </el-form-item>

          <el-form-item label="是否结项" prop="endProject">
            <template style="display: flex">
              <el-radio-group v-model="InfoForm.endProject">
                <el-radio label="1" style="width: 30%">是</el-radio>
                <el-radio label="2" style="width: 30%">否</el-radio>
              </el-radio-group>
            </template>
          </el-form-item>

          <el-form-item label="技术指标">
            <tinymce-editor
              ref="editor"
              v-model="InfoForm.specifications"
              @input="getInput"
            />
          </el-form-item>

          <el-form-item label="添加附件" prop="file">
            <el-upload
              class="upload-demo"
              :before-remove="beforeRemove"
              :on-change="fileChangeFunc"
              drag
              action=""
              multiple
              name="file"
              style="float: left"
              :file-list="fileList"
              :auto-upload="false"
            >
              <el-icon class="el-icon--upload"><Document /></el-icon>
              <div class="el-upload__text">
                拖放文件上传 或 <em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  单个文件最大为50MB,总上传大小为100MB
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('InfoForm')"
              >提交</el-button
            >
            <el-button @click="resetForm('InfoForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script>
import axios from "../../utils/request";
import { ElNotification } from "element-plus";
import { Document } from "@element-plus/icons";
import TinymceEditor from "@/components/TEditor";
export default {
  name: "addPaper",
  props: ["isOpen"],
  inject: ["reload"],
  components: { Document, TinymceEditor },
  data() {
    return {
      InfoForm: {
        projectType: 1,
        classification: "",
        selfPrice: "",
        cooperationUnit: "",
        financePrice: "",
        level: "",
        hostUnitId: -1,
        cooperationUnitId: -1,
        specifications:''
      },
      dialogFormToAdd: this.isOpen,
      useable: true,
      // 表单校验规则
      rules: {
        projectNum: [
          { required: true, message: "项目编号不允许为空", trigger: "blur" },
        ],
        projectName: [
          { required: true, message: "项目名称不允许为空", trigger: "blur" },
        ],
        hostname: [
          { required: true, message: "主持人不允许为空", trigger: "blur" },
        ],
        member: [
          { required: true, message: "团队成员不允许为空", trigger: "blur" },
        ],
        ranking: [
          { required: true, message: "本人排名不允许为空", trigger: "blur" },
          {
            min: 1,
            type: "number",
            message: "请输入大于0的整数",
            trigger: "blur",
          },
        ],
        hostUnit: [
          { required: true, message: "主持单位不允许为空", trigger: "blur" },
        ],
        beginDate: [
          {
            required: true,
            validator: this.checkBeginDate,
            trigger: "blur",
          },
        ],
        endDate: [
          {
            required: true,
            validator: this.checkEndDate,
            trigger: "blur",
          },
        ],
        totalPrice: [
          { required: true, message: "项目总金额不允许为空", trigger: "blur" },
          {
            min: 0,
            type: "number",
            message: "只允许输入大于等于0的数字",
            trigger: "blur",
          },
        ],
        projectType: [
          { required: true, message: "项目类型不允许为空", trigger: "blur" },
        ],
        cooperationUnit: [
          {
            required: true,
            validator: this.checkCooperationUnit,
            trigger: "blur",
          },
        ],
        level: [
          { required: true, validator: this.checkLevel, trigger: "blur" },
        ],
        classification: [
          {
            required: true,
            validator: this.checkClassification,
            trigger: "blur",
          },
        ],
        financePrice: [
          {
            required: true,
            validator: this.checkFinancePrice,
            trigger: "blur",
          },
          {
            min: 0,
            type: "number",
            message: "只允许输入大于等于0的数字",
            trigger: "blur",
          },
        ],
        selfPrice: [
          { required: true, validator: this.checkSelfPrice, trigger: "blur" },
          {
            min: 0,
            type: "number",
            message: "只允许输入大于等于0的数字",
            trigger: "blur",
          },
        ],
        endProject: [
          { required: true, message: "该字段不允许为空", trigger: "blur" },
        ],
      },
      fileList: [],
      files: [],
      restaurants: [],
      state: "",
    };
  },
  methods: {
    //表单提交
    submitForm(formName) {
      this.$refs.InfoForm.validate((valid) => {
        if (valid) {
          //录入人id写入
          this.InfoForm.enterUserId = this.$store.state.userInfo.userId;
          console.log(formName);
          var formData = new window.FormData();

          formData.append(
            "projectInfo",
            new Blob([JSON.stringify(this.InfoForm)], {
              type: "application/json",
            })
          );
          if (this.files.length != 0) {
            this.files.forEach((data) => {
              formData.append("file", data.raw);
            });
          }

          axios({
            method: "POST",
            url: "/ProjectInfo/add",
            headers: {
              "Content-Type": "multipart/form-data",
            },
            data: formData,
          }).then((res) => {
            if (res.data.status === 200) {
              ElNotification({
                message: res.data.message,
                type: "success",
              });
            }
            this.reload();
          });
        } else {
          return false;
        }
      });
    },
    //清空表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getLevelInfo() {
      axios.get("/ProjectLevel/ProjectLevelAll").then((reponse) => {
        if (reponse.data.status === 200) {
          this.level = reponse.data.data.projectLevel;
        }
      });
    },
    getClassicInfo() {
      var self = this;
      axios.get("/ProjectClassic/ProjectClassicAll").then((reponse) => {
        if (reponse.data.status === 200) {
          self.classic = reponse.data.data.projectClassic;
        }
      });
    },
    //选项禁用
    typeChange(val) {
      if (val === 1) {
        this.useable = true;
      } else {
        this.useable = false;
      }
      if (val === 2) {
        this.useable = false;
        this.InfoForm.cooperationUnit = "";
        this.InfoForm.level = "";
        this.InfoForm.classification = "";
        this.InfoForm.financePrice = "";
        this.InfoForm.selfPrice = "";
      }
    },
    getProjectType() {
      var self = this;
      axios.get("/ProjectType/ProjectTypeAll").then((reponse) => {
        if (reponse.data.status === 200) {
          self.projectType = reponse.data.data.projectType;
        }
      });
    },
    // 表单文件上传函数
    beforeRemove(file, fileList) {
      console.log(fileList);
      var re = this.$confirm(`是否删除文件 ${file.name} ?`)
        .then(() => {
          this.files.splice(this.files.indexOf(file), 1);
        })
        .catch(() => {
          return false;
        });
      return re;
    },
    fileChangeFunc(file, fileList) {
      // console.log("file :",file);
      this.files.push(file);
      console.log("fileList:", fileList);
    },
    hasAuth(perm) {
      var authority = this.$store.state.menus.permList;
      return authority.indexOf(perm) > -1;
    },

    /**
     * 自定义表单校验规则
     */

    //合作单位
    checkCooperationUnit(rule, value, callback) {
      if (this.InfoForm.projectType === 1) {
        if (value == "") {
          callback(new Error("合作单位不允许为空"));
        }
      }
      callback();
    },
    //项目级别
    checkLevel(rule, value, callback) {
      if (this.InfoForm.projectType === 1) {
        if (value == "") {
          callback(new Error("项目类别不允许为空"));
        }
      }
      callback();
    },
    //项目类别
    checkClassification(rule, value, callback) {
      if (this.InfoForm.projectType === 1) {
        if (value == "") {
          callback(new Error("项目类别不允许为空！"));
        }
      }
      callback();
    },
    //财政支持金额
    checkFinancePrice(rule, value, callback) {
      if (this.InfoForm.projectType === 1) {
        if (value == "") {
          callback(new Error("财政支持金额不允许为空"));
        } else if (value > this.InfoForm.totalPrice - this.InfoForm.selfPrice) {
          callback(new Error("不得大于项目总金额"));
        }
      }
      callback();
    },
    //自筹金额
    checkSelfPrice(rule, value, callback) {
      if (this.InfoForm.projectType === 1) {
        if (value == "") {
          callback(new Error("自筹金额不允许为空！"));
        } else if (
          value >
          this.InfoForm.totalPrice - this.InfoForm.financePrice
        ) {
          callback(new Error("不得大于项目总金额"));
        }
      }
      callback();
    },
    //起始日期
    checkBeginDate(rule, value, callback) {
      if (value == "" || value == null) {
        callback(new Error("起始时间不允许为空"));
      } else {
        let beginDate = new Date(value);
        let nowDate = new Date();

        if (beginDate > nowDate) {
          callback(new Error("起始时间不允许大于当前时间"));
        }
      }
      callback();
    },
    checkEndDate(rule, value, callback) {
      if (value == null || value == "") {
        callback(new Error("结项时间不允许为空"));
      } else {
        let endDate = new Date(value);
        let nowDate = new Date();
        let beginDate = new Date(this.InfoForm.beginDate);
        if (endDate < beginDate) {
          callback(new Error("结项时间不能小于起始时间"));
        } else if (endDate > nowDate) {
          callback(new Error("结项时间不能大于当前时间"));
        }
      }
      callback();
    },

    /**
     * 单位信息输入建议
     */
    //获取单位信息
    getCompanyInfo() {
      axios.get("/CompanyInfos/searchInput").then((res) => {
        // console.log(res);
        this.restaurants = res.data.data.map_companyInfo;
      });
    },
    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      cb(results);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.companyName.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelectHostUnit(item) {
      this.InfoForm.hostUnitId = item.id;
    },
    handleSelectCooperation(item) {
      this.InfoForm.cooperationUnitId = item.id;
    },
    getInput(input) {
      this.InfoForm.specifications = input;
    },
  },
  mounted() {
    this.getLevelInfo();
    this.getClassicInfo();
    this.getProjectType();
    this.getCompanyInfo();
  },
};
</script>
